package com.elepro.shoppingmall.config.security.handler;

import com.elepro.shoppingmall.entity.User;
import com.elepro.shoppingmall.service.user.UserServiceImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private UserServiceImpl userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        SecurityContext context = SecurityContextHolder.getContext();
        UserDetails userDetails = (UserDetails) context.getAuthentication().getPrincipal();
        String username = userDetails.getUsername();
        User user = userService.getUserByName(username);
        ResultMsg resultMsg = ResultMsg.success("登录成功", user);
        ResultMsg.returnResponse(resultMsg, httpServletResponse);
    }
}
